package com.chen.security;

import com.chen.pojo.Permission;
import com.chen.pojo.Role;
import com.chen.pojo.User;
import com.chen.service.UserServiec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Author zhebie
 * @DATE 2021/9/20
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Autowired
    private UserServiec userServiec;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名查询数据库，获取用户信息包含用户的所有角色及角色下的所有权限
        User user = userServiec.findByUsername(username);
        if (user==null){
            return null;
        }
        //构造返回的权限集合，授权，角色及权限
        //用户的权限集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        //获取用户下的所有角色
        Set<Role> userRoles = user.getRoles();
        if (!CollectionUtils.isEmpty(userRoles)){
            //遍历角色
            for (Role userRole : userRoles) {
                //授予角色
                SimpleGrantedAuthority sga = new SimpleGrantedAuthority(userRole.getKeyword());
                //【注意】要加入到权限集合中
                authorities.add(sga);
                //获取角色下的所有权限
                Set<Permission> permissions = userRole.getPermissions();
                //非空判断
                if (!CollectionUtils.isEmpty(permissions)){
                    //遍历授权
                    for (Permission permission : permissions) {
                        sga = new SimpleGrantedAuthority(permission.getKeyword());
                        authorities.add(sga);
                    }
                }
            }
        }
        //构造返回用户信息对象
        org.springframework.security.core.userdetails.User userInfo = new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorities);
        return userInfo;
    }
}
